package com.hngy.ip2region.service;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @name: Ip2RegionService
 * @Author: 提莫大熊猫
 * @Date: 2023/8/21
 */
@Service
public class Ip2RegionService {
    private byte[] cBuff;

    public Ip2RegionService() throws IOException {
        InputStream is = new ClassPathResource("ip2region.xdb").getInputStream();
        cBuff = FileCopyUtils.copyToByteArray(is);
        is.close();
    }

    /**
     * 获取 ip 归属地
     *
     * @param ip
     * @return
     */
    public String getIpLocation(String ip) {

        try {
            Searcher searcher = Searcher.newWithBuffer(cBuff);

            String[] region = searcher.search(ip).split("\\|");

            if ("中国".equals(region[0])) {
                return region[2];
            } else {
                return region[0];
            }

        } catch (Exception e) {
            return "未知";
        }

    }
}
